use 5.010;
use strict;
use warnings;

package JasPerl::JSTL::Core::OutTag;
use parent qw(JasPerl::TagExt::JspBodyTag);

use JasPerl::Util::Boolean;
use Scalar::Util qw(openhandle);

sub new {
    my $self = $_[0]->SUPER::new();
    $self->{escape_xml} = JasPerl::Util::Boolean::TRUE;
    return $self;
}

sub set_value {
    $_[0]->{value} = $_[1];
}

sub set_escape_xml {
    $_[0]->{escape_xml} = JasPerl::Util::Boolean->parse($_[1]);
}

sub set_default {
    $_[0]->{default} = $_[1];
}

sub copy {
    my ($self, $out, $fh) = @_;

    while (<$fh>) {
        $self->emit($out, $_);
    }
}

sub emit {
    my ($self, $out, $str) = @_;

    if ($self->{escape_xml}) {
        $str =~ s/&/&amp;/g;
        $str =~ s/</&lt;/g;
        $str =~ s/>/&gt;/g;
        $str =~ s/"/&#034;/g;
        $str =~ s/'/&#039;/g;
    }

    $out->print($str);
}

sub do_tag {
    my $self = shift;
    my $context = $self->get_jsp_context();
    my $out = $context->get_out();

    if (my $fh = openhandle($self->{value})) {
        $self->copy($out, $fh);
    } elsif (defined $self->{value}) {
        $self->emit($out, $self->{value});
    } elsif (exists $self->{default}) {
        $self->emit($out, $self->{default} // '');
    } else {
        $self->emit($out, $self->get_body_content());
    }
}

1;
